package com.etime.servlet;

import com.etime.entity.Student;
import com.etime.service.impl.ShowServiceImpl;
import com.etime.service.impl.StudentServiceImpl;
import com.etime.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/showServlet")
public class ShowServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");
    if (req.getParameter("name")!=null && req.getParameter("password")!=null){
      if (req.getParameter("name").equals("") && req.getParameter("password").equals("")){
        ShowServiceImpl showService = new ShowServiceImpl();
        int size = showService.show().size();
        int page = 1;
        int rows = 5;
        StudentServiceImpl studentService = new StudentServiceImpl();
        String flag = req.getParameter("flag");
        if ("limitSelect".equals(flag)){
          page = Integer.parseInt(req.getParameter("page"));
        }
        PageUtil pageUtil = new PageUtil(page, rows, size);
        List<Student> students = studentService.limitSelect(pageUtil.getIndex(), pageUtil.getRows());
        req.setAttribute("list", students);
        req.setAttribute("pageUtil", pageUtil);
        req.getRequestDispatcher("show.jsp").forward(req, resp);
      }
      else {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        Student student = new Student();
        student.setName(name);
        student.setPassword(password);
        StudentServiceImpl studentService = new StudentServiceImpl();
        List<Student> select = studentService.select(student);
        req.setAttribute("list", select);
        req.getRequestDispatcher("show.jsp").forward(req, resp);
      }
    }
    else {
      ShowServiceImpl showService = new ShowServiceImpl();
      int size = showService.show().size();
      int page = 1;
      int rows = 5;
      StudentServiceImpl studentService = new StudentServiceImpl();
      String flag = req.getParameter("flag");
      if ("limitSelect".equals(flag)){
        page = Integer.parseInt(req.getParameter("page"));
      }
      PageUtil pageUtil = new PageUtil(page, rows, size);
//      List<Student> students = showService.show();
      List<Student> students = studentService.limitSelect(pageUtil.getIndex(), pageUtil.getRows());
//    PrintWriter writer = resp.getWriter();
//    for (Student i : students){
//      writer.print(i);
//    }
//    writer.close();
      req.setAttribute("list", students);
      req.setAttribute("pageUtil", pageUtil);
      req.getRequestDispatcher("show.jsp").forward(req, resp);
    }
  }
}
